/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.manager;

import com.icee.myth.common.AbstractServer;
import com.icee.myth.common.message.serverMessage.InternalChannelMessage;
import com.icee.myth.common.message.serverMessage.Message;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;
import org.jboss.netty.channel.Channel;

import java.util.Collection;
import java.util.TreeMap;

/**
 * 服务器与服务器通信，Console服务器（客户端）连Manager服务器（服务器）
 * @author liuxianke
 */
public class ConsoleToManagerServer extends AbstractServer {
    public final TreeMap<Integer, Channel> consoleChannels = new TreeMap<Integer, Channel>();

    //Singleton
    private static ConsoleToManagerServer INSTANCE = new ConsoleToManagerServer();

    //getInstance操作的第一次调用在Main的start中，因此无需同步
    public static ConsoleToManagerServer getInstance() {
        return INSTANCE;
    }

    private ConsoleToManagerServer() {
    }

    @Override
    public void closeServer() {
        super.closeServer();

        for (Channel consoleChannel : consoleChannels.values()) {
            consoleChannel.close();
        }
    }

    private void clientClose(Channel channel) {
        if (consoleChannels.remove(channel.getId()) != null) {
            MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Console["+channel.getRemoteAddress()+"] closed.");
        }
    }

    public Collection<Channel> getConsoleChannels() {
        return consoleChannels.values();
    }

    public void handleMessage(Message message) {
        switch (message.getType()) {
            case MANAGER_CONSOLE_CONNECT: {
                // 处理Deamon Connect消息
                InternalChannelMessage channelMessage = (InternalChannelMessage)message;
                Channel channel = channelMessage.channel;
                
//                if (consoleChannel == null) {
                if (!consoleChannels.containsKey(channel.getId())) {
                    // 判定Console ip是否合法
                    String consoleIP = channel.getRemoteAddress().toString();
                    consoleIP = consoleIP.substring(1, consoleIP.indexOf(":"));
                    if (Manager.INSTANCE.isTrustedConsole(consoleIP)) {
                        // TODO: 认证Console权限（用状态机）
                        consoleChannels.put(channel.getId(), channel);
//                        consoleChannel = channel;
                        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Console["+channel.getRemoteAddress()+"] connected.");
                    } else {
                        channel.close();
                        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Console["+channel.getRemoteAddress()+"] not a trusted console.");
                    }
                } else {
                    channel.close();
                    MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Multi-connect failed.");
                }
//                } else {
//                    channel.close();
//                    MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "connect failed, Console["+consoleChannel.getRemoteAddress()+"] is connecting.");
//                }
                break;
            }
            case MANAGER_CONSOLE_CLOSE: {
                // 处理Deamon Close消息
                clientClose(((InternalChannelMessage)message).channel);
                break;
            }
            default:
                System.out.println("unknow case");
                break;
        }
    }
}
